﻿using System;
using System.Data;
using System.Xml;

namespace sqlserverextensions.ExportOperations
{
    internal class Xml : IDisposable
    {
        private Boolean disposedValue;
        private XmlWriter writer;


        internal Xml(string fileName, string rootNodeName)
        {
            XmlWriterSettings settings = new XmlWriterSettings();
            settings.Indent = true;
            settings.NewLineOnAttributes = true;

            this.writer = XmlWriter.Create(fileName, settings);
            this.writer.WriteStartDocument();
            this.writer.WriteStartElement(rootNodeName);
        }

        internal void Close()
        {
            if (this.writer != null)
            {
                this.writer.WriteEndElement();
                this.writer.WriteEndDocument();
                this.writer.Flush();
                this.writer.Close();
                this.writer = null;
            }
        }

        internal void ElementStart(string name)
        {
            this.writer.WriteStartElement(name);
        }

        internal void ElementEnd()
        {
            this.writer.WriteEndElement();
            this.writer.Flush();
        }

        internal void AttributeString(string name, string value)
        {
            this.writer.WriteAttributeString(name, value);
        }

        internal void WriteHeaderCell(DataColumn col)
        {
            this.writer.WriteStartElement(col.ColumnName);
            this.writer.WriteAttributeString("datatype", col.DataType.ToString());
            this.writer.WriteEndElement();
        }

        internal void WriteHeaderCell(string name, string dataType)
        {
            this.writer.WriteStartElement(name);
            this.writer.WriteAttributeString("datatype", dataType);
            this.writer.WriteEndElement();
        }

        internal void WriteDataCell(string colName, string value)
        {
            this.writer.WriteStartElement(colName);
            this.writer.WriteAttributeString("value", value);
            this.writer.WriteEndElement();
        }

        protected void Dispose(Boolean disposing)
        {
            if (!this.disposedValue)
            {
                if (disposing)
                {
                    if (this.writer != null)
                    {
                        this.Close();
                        this.writer = null;
                    }
                }
            }

            this.disposedValue = true;
        }

        public void Dispose()
        {
            this.Dispose(true);
            GC.SuppressFinalize(this);
        }
    }
}